import Request from './request'
import configs from '@/config/index.js'
const http = new Request()
import store from '@/store/index.js'
let versionCode = ''
let os = 'android'


http.setConfig((config) => { /* 设置全局配置 */
	config.baseUrl = configs.baseUrl /* 根域名不同 */
	return config
})
// 响应判断校验器
http.validateStatus = (response) => {
	if (response.statusCode !== 200) {
		return false
	}
	if (response.data) {
		const {
			error,
			code,
			status
		} = response.data

		if (code == 40000) {
			return true
		} else {
			return false
		}
	}
	return true
}

/* 请求之前拦截器 */
http.interceptor.request(async (config, cancel) => {
	// 通过config携带isAuth来判断是否需要带上token
	if (config && config.loading) {
		uni.showLoading()
	}
	// 携带版本号和系统
	if (!versionCode) {
		// #ifdef APP-PLUS
		versionCode = plus.runtime.version.replace(/\./g, "")
		// #endif
	}

	config.header = {
		...config.header,
		'version-code': versionCode,
		os: os
	}
	// console.log(config.header)
	if (!config.noAuth) {
		if (!store.state.token) {
			store.state.token = uni.getStorageSync('auth')
		}
		let token = store.state.token

		config.header = {
			'jwt-token': token,
			...config.header,
		}
	}

	return config
})

/* 请求之后拦截器 */
http.interceptor.response((response) => { /* 请求之后拦截器 */
	if (response.config && response.config.loading) {
		uni.hideLoading()
	}
	const resp = response.data
	return resp.data
}, async (response) => {
	if (response.config && response.config.loading) {
		uni.hideLoading()
	}
	const resp = response.data
	if (resp.code == 50000) {
		uni.showToast({
			title: resp.msg,
			icon: 'none',
			duration: 2000
		})
	}
	if (resp.code == 50003) {
		if (store.state.lock > 0) return Promise.reject(response.data)
		store.state.lock++
		store.state.token = ''

		uni.clearStorage()
		uni.reLaunch({
			url: '/pages/login/index'
		})
	}
	if (resp.code == 50005) {
		if (store.state.updateLock > 0) return Promise.reject(response.data)
		store.state.updateLock++
		uni.reLaunch({
			url: '/pages/login/update',
		})
	}
	return response.data
})

export {
	http
}
